package hyl.core.struct;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 我想构造一个类似于window 底层的消息框架 只用于当前java程序环境
 * 
 * 消息被监听的组件使用后,继续向后抛送(层层消费)
 * 
 * 
 * 
 * @author 37798955@qq.com
 *
 */
public class DataQueue<T> {
	// 消息队列
	final ConcurrentLinkedQueue<T> queue;

	public DataQueue() {

		queue = new ConcurrentLinkedQueue<>();
	}

	public void push(T 元素) {
		锁.lock();
		try {
			queue.add(元素);
			开关.signal();
		} finally {
			锁.unlock();
		}
	}

	// 锁
	private Lock 锁 = new ReentrantLock();
	// 开关
	public Condition 开关 = 锁.newCondition();

	public T pollData() {
		T icd = null;
		锁.lock();
		try {
			// _当前处理队列.
			while ((icd = queue.poll()) == null) {
				try {
					开关.await(100, TimeUnit.MILLISECONDS);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		} finally {
			锁.unlock();
		}
		return icd;

	}

}
